package org.codeworks.dsp.utils;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.net.URL;

/**
 * Created by benjaminkc on 16/12/11.
 */
public class EhcacheUtil {

    //private static final String path = "/ehcache.xml";

    private URL url;

    private CacheManager manager;

    private static EhcacheUtil ehCache;

    private EhcacheUtil() {
        Resource resource = new ClassPathResource("config/xml/ehcache.xml");

        //url = getClass().getResource(path);
        try {
            url = resource.getURL();
        }catch (IOException ex){
            throw new RuntimeException("ehcache.xml can not found!!!");
        }
        manager = CacheManager.create(url);
    }

    public static EhcacheUtil getInstance() {
        if (ehCache== null) {
            ehCache= new EhcacheUtil();
        }
        return ehCache;
    }

    public void put(String cacheName, String key, Object value) {
        Cache cache = manager.getCache(cacheName);
        Element element = new Element(key, value);
        cache.put(element);
        cache.flush();
    }

    public Object get(String cacheName, String key) {
        Cache cache = manager.getCache(cacheName);
        Element element = cache.get(key);
        return element == null ? null : element.getObjectValue();
    }

    public Cache get(String cacheName) {
        return manager.getCache(cacheName);
    }

    public void remove(String cacheName, String key) {
        Cache cache = manager.getCache(cacheName);
        cache.remove(key);
        cache.flush();
    }

    public void removeAll(){
        manager.removeAllCaches();
    }

    public void removeCache(String cacheName){
        manager.removeCache(cacheName);
    }
}
